<template>
	<view class="content">
		<navBar>
			<template @click="backPage()" slot='left'>
				<u-icon name="arrow-left" color="#fff"></u-icon>
			</template>
			<template class="centerText" slot='center'>
				<view class="" style="color: #fff;">
					{{title}}
				</view>
			</template>
		</navBar>
		<!-- 信息录入 -->
		<view class="information_entry">
			<u--form labelPosition="left" ref="uForm" labelWidth='80' :model="formData" :rules="rules">
				<u-form-item required label="货物名称" prop="goods_name" borderBottom ref="item1">
					<u--input v-model="formData.goods_name" disabledColor="#ffffff" placeholder="请输入货名称"
						border="none"></u--input>
				</u-form-item>
				<u-form-item label="货物图片" prop="cargoName" borderBottom ref="item1">
					<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
						:maxCount="1" deletable>
						<template>
							<view class="upload_box">+</view>
						</template>
					</u-upload>
				</u-form-item>
				<u-form-item required label="货物编码" prop="goods_no" borderBottom ref="item1">
					<u--input v-model="formData.goods_no" disabledColor="#ffffff" placeholder="请输入货物编码"
						border="none"></u--input>
					<!-- <u-icon slot="right" name="scan" size="28" color="#2979ff"></u-icon> -->
				</u-form-item>
				<u-form-item label="货物单价" borderBottom ref="item1">
					<u--input type='number' v-model="formData.price" disabledColor="#ffffff" placeholder="请输入货物单价"
						border="none"></u--input>
				</u-form-item>
				<u-form-item required label="库存警告" prop="stock_low" borderBottom ref="item1">
					<u--input type='number' v-model.number="formData.stock_low" disabledColor="#ffffff"
						placeholder="请输最低库存" border="none"></u--input>
				</u-form-item>
				<u-form-item label="货物分类" @click="selectCategory()" prop="cargoCategory" borderBottom ref="item1">
					<!-- <u--input disabled v-model="formData.cate_id" disabledColor="#ffffff" placeholder="请选择分类"
						border="none"></u--input> -->
					{{cate_name}}
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item @click="selectUnit()" label="计量单位" prop="unit" borderBottom ref="item1">
					<u--input disabled type='number' v-model="formData.unit" disabledColor="#ffffff"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item @click="selectBrand()" label="货物品牌" prop="brand_id" borderBottom ref="item1">
					{{brand_name}}
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>

				<u-form-item label="货物规格" prop="spec" borderBottom ref="item1">
					<u--input v-model="formData.spec" disabledColor="#ffffff" placeholder="请输入规格"
						border="none"></u--input>
				</u-form-item>
				<u-form-item @click="clickShowStatusPicker()" label="状态" prop="status" borderBottom ref="item1">
					<!-- <u--input v-model="formData.status" disabledColor="#ffffff" placeholder="请输入名称"
						border="none"></u--input> -->
					{{formData.status == 1 ? '正常' : '停用'}}
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="需归还" @click="clickShowBackPicker()" prop="is_back" borderBottom ref="item1">
					<!-- <u--input v-model="formData.is_back" disabledColor="#ffffff" placeholder="请输入名称"
						border="none"></u--input> -->
					{{formData.is_back == 1 ? '需要归还' : '无需归还'}}
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>

				<u-form-item label="货物库存" prop="goods_num" borderBottom ref="item1">
					<u--input :disabled='disabled' type='number' v-model.number="formData.goods_num"
						disabledColor="#ffffff" placeholder="请输入货物库存" border="none"></u--input>
				</u-form-item>
				<template v-if="loadMoreFlag">
					<u-form-item label="库存容量" prop="stock_high " borderBottom ref="item1">
						<u--input type='number' v-model.number="formData.stock_high" disabledColor="#ffffff"
							placeholder="请输入库存容量上限" border="none"></u--input>
					</u-form-item>
					<u-form-item label="取用上限" prop="max_take" borderBottom ref="item1">
						<u--input type='number' v-model.number="formData.max_take" disabledColor="#ffffff"
							placeholder="请输入货物取用上限" border="none"></u--input>
					</u-form-item>
					<u-form-item label="30天上限" prop="month_limit" borderBottom ref="item1">
						<u--input type='number' v-model.number="formData.month_limit" disabledColor="#ffffff"
							placeholder="请输入30天内取用上限" border="none"></u--input>
					</u-form-item>

					<u-form-item @click="clickShowLifePicker()" label="货物寿命" prop="is_life" borderBottom ref="item1">
						<!-- <u--input v-model="formData.is_life" disabledColor="#ffffff" placeholder="请输入名称"
							border="none"></u--input> -->
						{{formData.is_life == 1? '开启' : '关闭'}}
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item label="额定寿命" prop="goods_life" borderBottom ref="item1">
						<u--input v-model="formData.goods_life" disabledColor="#ffffff" placeholder="请输入额定寿命"
							border="none"></u--input>
					</u-form-item>

					<u-form-item label="备注信息" borderBottom>
						<u--textarea v-model="formData.remark" maxlength="50" count placeholder="请输入内容"></u--textarea>
					</u-form-item>
				</template>
				<loadMore :loadMoreFlag.sync='loadMoreFlag'></loadMore>
			</u--form>
		</view>
		<!-- 提交 -->
		<view class="bottom_box">
			<view class="submit_btn">
				<u-button @click="saveSubmit()" color="#39cccc" shape='circle' type="primary" text="提交"></u-button>
			</view>
		</view>
		<!-- 选择类别弹出层 -->
		<selectCategoryPopup :categoryList=categoryList :showPopup.sync="showPopup"></selectCategoryPopup>
		<!-- 选择品牌弹出层 -->
		<selectBrandPopup :brandList=brandList :showBrandPopup.sync='showBrandPopup'></selectBrandPopup>
		<!-- 计量单位选择弹出层 -->
		<selectUnitPopup :showUnitPopup.sync='showUnitPopup'></selectUnitPopup>
		<!-- 状态选择器 -->
		<u-picker keyName="label" @confirm=statusPickerConfrim() :show="showStatusPicker"
			@cancel="showStatusPicker = false" :columns="columnsStatus"></u-picker>
		<!-- 是否开启货物寿命 -->
		<u-picker keyName="label" @confirm=lifePickerConfrim() :show="showLifePicker" @cancel="showLifePicker = false"
			:columns="columnsLife"></u-picker>
		<!-- 是否需要归还 -->
		<u-picker keyName="label" @confirm=backPickerConfrim() :show="showBackPicker" @cancel="showBackPicker = false"
			:columns="columnsBack"></u-picker>
	</view>
</template>

<script>
	import navBar from '@/components/navBar.vue'
	import selectCategoryPopup from './components/selectCategoryPopup.vue'
	import selectBrandPopup from './components/selectBrandPopup.vue'
	import selectUnitPopup from './components/selectUnitPopup.vue'
	import loadMore from '@/components/loadMore.vue'
	import {
		getBrandListApi
	} from '@/api/brandManage.js'
	import {
		getCategoryListApi,
		addGoodsApi,
		generateBarcodeApi,
		editGoodsApi
	} from '@/api/categoryManage.js'

	export default {
		data() {
			return {
				formData: {
					goods_name: '', //名称
					goods_no: '', // 编码
					goods_num: '', // 库存
					// goods_img: '', //图片
					unit: '', //单位
					spec: '', //规格
					ware_id: this.$store.state.user.stashInfo.ware_id, //仓库
					brand_id: '', //品牌id
					cate_id: '', //分类ID
					stock_low: '', //库存预警
					stock_high: '', //库存上限
					price: '', //价格
					status: 1, //货物状态
					goods_life: '', //额定寿命
					is_life: '', // 是否开启货物寿命
					is_back: 1, //是否归还
					max_take: '', //取用上限
					month_limit: '', //30天取用上限
					remark: '', //备注
				},
				loadMoreFlag: false,
				disabled: false,
				showStatusPicker: false, // 状态选择器
				showLifePicker: false, //寿命
				showBackPicker: false, //需归还
				//状态
				columnsStatus: [
					[{
						label: '正常',
						id: 1
					}, {
						label: '停用',
						id: 2
					}]
				],
				//寿命
				columnsLife: [
					[{
						label: '开启',
						flag: true
					}, {
						label: '关闭',
						flag: false
					}]
				],
				//需归还
				columnsBack: [
					[{
						label: '需要归还',
						id: 1
					}, {
						label: '无需归还',
						id: 2
					}]
				],
				title: '添加货物',
				fileList1: [],
				cate_name: '', // 分类名
				brand_name: '', //品牌名
				brandList: [], //品牌列表
				categoryList: [], //分类列表
				showPopup: false,
				showBrandPopup: false,
				showUnitPopup: false,
				rules: {
					goods_name: {
						required: true,
						message: '请填输入名称',
						trigger: ['blur'],
					},
					goods_no: {
						required: true,
						message: '请输入货物编码',
						trigger: ['blur']
					},
					price: {
						required: true,
						message: '请输货物单价',
						trigger: ['blur']
					},
					stock_low: {
						required: true,
						message: '请输库存预警',
						trigger: ['blur']
					},
				},
			};
		},
		onShow() {
			this.getBrandList()
			this.getCategoryList()
		},
		onLoad(e) {
			if (e.goodsInfo) {
				const res = JSON.parse(e.goodsInfo)
				if (res.goods_img != '' && res.goods_img != '/static/images/shixiao.png') {
					this.fileList1.push({
						url: res.goods_img
					})
				}
				this.formData = res
				this.formData.price = this.formData.price + ''
				this.formData.stock_low = this.formData.stock_low + ''
				this.cate_name = res.cate_name
				this.brand_name = res.brand_name
				this.title = '编辑货物'
				this.disabled = true
			} else {
				this.generateBarcode()
			}
		},
		components: {
			navBar,
			selectCategoryPopup,
			selectBrandPopup,
			selectUnitPopup,
			loadMore
		},
		methods: {
			// 获取品牌列表
			async getBrandList(pageInfo) {
				const {
					data: {
						data: {
							list
						}
					}
				} = await getBrandListApi(pageInfo ? pageInfo : {
					page: 1,
					pageSize: 100,
				})
				this.brandList = list
			},
			//获取分类列表
			async getCategoryList(pageInfo) {
				const {
					data: {
						data: {
							list
						}
					}
				} = await getCategoryListApi(pageInfo ? pageInfo : {
					page: 1,
					pageSize: 100,
				})
				this.categoryList = list
			},
			//生成条码
			async generateBarcode() {
				const {
					data: {
						data
					}
				} = await generateBarcodeApi()
				this.formData.goods_no = data
			},
			backPage() {
				// const that = this
				// uni.showModal({
				// 	content: '数据还没有提交确定退出吗',
				// 	success: function(res) {
				// 		if (res.confirm) {
				// 			uni.navigateBack();
				// 		} else if (res.cancel) {
				// 			console.log('用户点击取消');
				// 		}
				// 	}
				// });
				uni.navigateBack();
			},
			// 选择类别
			selectCategory() {
				this.showPopup = true

				this.getCategoryList()
			},
			// 选择品牌
			selectBrand() {
				this.showBrandPopup = true
				this.getBrandList()
			},
			// 选择单位
			selectUnit() {
				this.showUnitPopup = true
			},
			// 状态选择器
			clickShowStatusPicker() {
				this.showStatusPicker = true
			},
			//状态确定
			statusPickerConfrim(e) {
				this.formData.status = e.value[0].id
				this.showStatusPicker = false
			},
			//寿命选择器
			clickShowLifePicker() {
				this.showLifePicker = true
			},
			//寿命
			lifePickerConfrim(e) {
				this.formData.is_life = e.value[0].flag
				// console.log(this.formData.is_life);
				// this.is_life_text = e.value[0].label
				this.showLifePicker = false
			},
			// 需归还选择器
			clickShowBackPicker() {
				this.showBackPicker = true
			},
			//需归还
			backPickerConfrim(e) {
				this.formData.is_back = e.value[0].id
				this.showBackPicker = false
			},
			//保存
			async saveSubmit() {
				const data = {
					...this.formData,
					goods_img: this.fileList1[0] ? this.fileList1[0].url : ''
				}
				data.price = data.price * 1
				data.goods_num = data.goods_num * 1
				data.stock_low = data.stock_low * 1
				data.stock_high = data.stock_high * 1
				data.max_take = data.max_take * 1
				data.month_limit = data.month_limit * 1
				data.goods_life = data.goods_life * 1
				await this.$refs.uForm.validate()
				if (this.title == '编辑货物') {
					await editGoodsApi(data)
					uni.$u.toast('编辑成功')
					setTimeout(() => {
						this.backPage()
					}, 1000)
				} else {
					await addGoodsApi(data)
					uni.$u.toast('新增成功')
					setTimeout(() => {
						this.backPage()
					}, 1000)
				}
				// this.$refs.uForm.validate().then(res => {
				// 	uni.$u.toast('校验通过')
				// }).catch(errors => {
				// 	uni.$u.toast('校验失败')
				// })
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: 'success',
							message: '',
							url: result
						})
					);
					fileListLen++;
				}
			},
			uploadFilePromise(url) {
				const that = this
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'https://api.wanwucloud.cn/api/upload/img', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						header: {
							AuthorToken: this.$store.state.user.userInfo.token
						},
						success: (res) => {
							let successRes = JSON.parse(res.data)
							if (successRes.code == 200) {
								uni.hideLoading();
								setTimeout(() => {
									resolve(successRes.data.url);
									uni.$u.toast(successRes.msg)
								}, 100);
							} else {
								uni.hideLoading();
								uni.$u.toast(successRes.msg)
							}
						}
					});
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.content {

		background-color: #e0ecfa;


		.information_entry {
			background-color: #fff;
			margin: 10rpx 10rpx 180rpx;
			padding: 30rpx 20rpx;
			border-radius: 20rpx;

			::v-deep .u-form-item__body__left {
				margin-left: 20rpx;
			}

			::v-deep .u-upload__wrap__preview {
				width: 110rpx;
				height: 110rpx;
			}

			::v-deep .u-upload__wrap__preview__image {
				width: 110rpx !important;
				height: 110rpx !important;
			}
		}

		.bottom_box {
			display: flex;
			justify-content: center;
			align-items: center;
			position: fixed;
			bottom: 0;
			width: 100%;
			height: 160rpx;
			background-color: #f0f3f8;
			z-index: 99;

			.submit_btn {
				width: 600rpx;
			}
		}

		.upload_box {
			width: 110rpx;
			height: 110rpx;
			border: 1px dashed #ccc;
			text-align: center;
			line-height: 110rpx;
			font-size: 40rpx;
			color: #ccc;
		}
	}
</style>